package com.gitee.xmhzzz.component.shutdown.graceful;

import com.gitee.xmhzzz.component.shutdown.graceful.config.ShutdownConfig;
import com.gitee.xmhzzz.component.shutdown.graceful.event.ApplicationShutdownEvent;
import com.gitee.xmhzzz.component.shutdown.graceful.tomcat.GracefulShutdownTomcatInitializer;
import com.gitee.xmhzzz.component.shutdown.graceful.tomcat.TomcatShutdown;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

/**
 * @ClassName ShutdownGracefulConfiguration
 * @Description
 * @Author wzq
 * @Date 2023/9/25 11:21
 * @Version 1.0
 */
@EnableConfigurationProperties(ShutdownConfig.class)
@ConditionalOnProperty(value = "yipule.component.shutdown.enable", havingValue = "true")
@ComponentScan("com.gitee.xmhzzz.component.shutdowngraceful.*")
@Slf4j
public class ShutdownGracefulConfiguration {

    public ShutdownGracefulConfiguration(ApplicationContext applicationContext) {
        log.info("ShutdownHookAutoConfiguration init..........");
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            applicationContext.publishEvent(new ApplicationShutdownEvent(applicationContext));
        }));
    }
    @Bean
    @ConditionalOnMissingClass({"xmhzzz.graceful.shutdown.enable"})
    public TomcatShutdown gracefulShutdownTomcat( ) {
        if (log.isDebugEnabled()) {
            log.debug("[优雅停机组件]-自定义 Tomcat 优雅停机...");
        }
        return new TomcatShutdown(30);
    }

    @Bean
    @ConditionalOnMissingClass(value = {"xmhzzz.graceful.shutdown.enable"})
    public GracefulShutdownTomcatInitializer gracefulShutdownTomcatInitializer(TomcatShutdown gracefulShutdownTomcat) {
        if (log.isDebugEnabled()) {
            log.debug("[优雅停机组件]-启动 Tomcat 优雅停机...");
        }
        return new GracefulShutdownTomcatInitializer(gracefulShutdownTomcat);
    }
}
